﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace PasteCodeTaskBase
{
    /// <summary>
    /// 
    /// </summary>
    [ApiController]
    [Route("/api/taskclient/[action]")]
    public class TaskClientController : ControllerBase
    {
        private TaskChannelHelper _channelHelper;
        private readonly ILogger<TaskClientController> _logger;
        private TaskNodeConfig _config;

        public TaskClientController(TaskChannelHelper task, IOptions<TaskNodeConfig> config, ILogger<TaskClientController> logger)
        {
            _channelHelper = task;
            _config = config.Value;
            _logger = logger;
        }

        /// <summary>
        /// 服务端发送运行任务申请
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public int dowork(PasteTaskSharedModel info)
        {
            _logger.LogInformation($"dowork:{Newtonsoft.Json.JsonConvert.SerializeObject(info)}");
            //如果是slave节点的如何校验... .. .
            var tokencheck = false;
            if (base.Request.Headers.ContainsKey("xtoken"))
            {
                var xtoken = base.Request.Headers["xtoken"].ToString();
                var strs = xtoken.Split('_');
                if (strs.Length >= 3)
                {
                    var s1 = strs[0];
                    var s2 = strs[1];
                    var s3 = strs[2];
                    //检验s1和当前时间的差距是否过大
                    //System.DateTimeOffset.Now.ToUnixTimeSeconds();
                    if ($"{s1}_{s2}_{_config.JoinToken}".ToMd5Lower() == s3)
                    {
                        tokencheck = true;
                        //任务写入到队列中去
                        _channelHelper.WriteChannel(info);
                    }
                    else
                    {
                        _logger.LogError($"revice do work throw error! xtoken:{xtoken} is error! url is:{_config.Url} config.jointoken:{_config.JoinToken}");
                        //System.Console.WriteLine($"{DateTime.Now} send work to client error token error:{xtoken}");
                    }
                }
                else
                {
                    _logger.LogWarning("TaskClientController.dowork.xtoken.length error!");
                    return 500;
                }
            }
            if (!tokencheck)
            {
                throw new System.Exception("xtoken error!");
            }
            return 1;
        }

        /// <summary>
        /// 健康检查模式
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public long health()
        {

            return System.DateTimeOffset.Now.ToUnixTimeSeconds();
        }
    }
}
